<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/admin/AdminAction.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/Response.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Person.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Error.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Pattern.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Str.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

final class PersonUpdateAction extends AdminAction {
	protected function execute(Response $response) {
		$person = null;
		if(isset($_POST['login']) &&
				Str::isMatch(Pattern::LOGIN, $_POST['login']) &&
				isset($_POST['surname']) &&
				Str::isMatch(Pattern::WORD, $_POST['surname']) &&
				isset($_POST['name']) &&
				Str::isMatch(Pattern::WORD, $_POST['name'])) {
			$person = new Person();
			$person->setLogin($_POST['login']);
			$person->setSurname($_POST['surname']);
			$person->setName($_POST['name']);
			if(isset($_POST['patronymic']) &&
					Str::isMatch(Pattern::WORD, $_POST['patronymic'])) {
				$person->setPatronymic($_POST['patronymic']);
			}
			$serviceFactory = new ServiceFactory();
			$service = $serviceFactory->getService('PersonService');
			if(isset($_POST['identity'])) {						// переделываем!!!!!
				$person->setIdentity($_POST['identity']);
			}
			$person = $service->save($person);

			if($person === null) {
				$response->setError(Error::UNIQUE_PERSON_LOGIN_ERROR);
			}
		}
		if($response->getError() === null) {
			if($person !== null) {
				$_SESSION['person-identity'] = $person->getIdentity();
				$response->setActionPath('/person/edit.html');
			} else {
				$response->setActionPath('/person/index.html');
			}
		}
	}
}
?>